import { Module } from 'vuex'

const baseUrl = config.baseUrl

const user: Module<UserState, UserState> = {
    state: {
        token: getToken(),
        nickName: storage.get(constant.nickName),
        avatar: storage.get(constant.avatar),
        roles: storage.get(constant.roles),
        permissions: storage.get(constant.permissions)
    },
    mutations: {
        SET_TOKEN: (state, token: string) => {
            state.token = token
        },
        SET_NICKNAME: (state, name: string) => {
            state.nickName = name
            storage.set(constant.nickName, name)
        },
        SET_AVATAR: (state, avatar: string) => {
            state.avatar = avatar
            storage.set(constant.avatar, avatar)
        },
        SET_ROLES: (state, roles: Array<string>) => {
            state.roles = roles
            storage.set(constant.roles, roles)
        },
        SET_PERMISSIONS: (state, permissions: Array<string>) => {
            state.permissions = permissions
            storage.set(constant.permissions, permissions)
        }
    },

    actions: {
        // 登录
        Login({ commit }, userInfo: UserForm) {
            return new Promise((resolve, reject) => {
                login(userInfo).then((res: any) => {
                    if(res && res.code === 200) {
                        const data = res.data;
                        setToken(data.token)
                        commit('SET_TOKEN', data.token)
                        resolve(res.code)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetInfo({ commit }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then((res: any) => {
                    if (res && res.code === 200) {
                        const data = res.data;
                        const avatar = (user == null || data.avatar == "" || data.nickName == null) ? "/static/images/profile.jpg" : baseUrl + data.avatar
                        const nickName = (user == null || data.nickName == "" || data.nickName == null) ? "" : data.nickName
                        commit('SET_NICKNAME', nickName)
                        commit('SET_AVATAR', avatar)
                    }
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 退出系统
        // LogOut({ commit, state }) {
        //   return new Promise((resolve, reject) => {
        //     logout().then((res) => {
        //       commit('SET_TOKEN', '')
        //       commit('SET_ROLES', [])
        //       commit('SET_PERMISSIONS', [])
        //       removeToken()
        //       storage.clean()
        //       resolve(res)
        //     }).catch(error => {
        //       reject(error)
        //     })
        //   })
        // }
    }
}

export default user